package com.bilibili.juc.cf.one;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/*
创建异步任务

    supplyAsync执行CompletableFuture任务，支持返回值
    runAsync执行CompletableFuture任务，没有返回值。

supplyAsync方法

//使用默认内置线程池ForkJoinPool.commonPool()，根据supplier构建执行任务
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
//自定义线程，根据supplier构建执行任务
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)

runAsync方法

//使用默认内置线程池ForkJoinPool.commonPool()，根据runnable构建执行任务
public static CompletableFuture<Void> runAsync(Runnable runnable)
//自定义线程，根据runnable构建执行任务
public static CompletableFuture<Void> runAsync(Runnable runnable,  Executor executor)


 */
public class FutureTest {

    public static void main(String[] args) {
        //可以自定义线程池
        ExecutorService executor = Executors.newCachedThreadPool();
        //runAsync的使用
        CompletableFuture<Void> runFuture = CompletableFuture.runAsync(() ->
                System.out.println("run,关注公众号:捡田螺的小男孩"), executor);
        //supplyAsync的使用
        CompletableFuture<String> supplyFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("supply,关注公众号:捡田螺的小男孩");
            return "捡田螺的小男孩";
        }, executor);
        //runAsync的future没有返回值，输出null
        System.out.println(runFuture.join());
        //supplyAsync的future，有返回值
        System.out.println(supplyFuture.join());
        //supplyFuture.get(); //get()方法也是阻塞获得CompletableFuture返回结果值，不过这个方法会抛出异常
        //还有一个等待重载的方法
        // java.util.concurrent.CompletableFuture.get()
//        supplyFuture.get()
        // java.util.concurrent.CompletableFuture.get(long, java.util.concurrent.TimeUnit)
        //supplyFuture.get(2, TimeUnit.SECONDS);
        executor.shutdown(); // 线程池需要关闭
    }
}
//输出
/*
run,关注公众号:捡田螺的小男孩
null
supply,关注公众号:捡田螺的小男孩捡田螺的小男孩*/
